package com.huang.wangpan.schedule;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordResponse;
import com.huang.wangpan.vo.IpInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yh
 * @Date: 2020/6/21
 * @Description:
 */
// @Component
// @EnableScheduling
public class IP6ScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(IP6ScheduleTask.class);

    @Autowired
    Ipv6Interface ipv6Interface;

    @Autowired
    OperateDomain operateDomain;

    Map<String, Object> recordMap = new HashMap<>();

    // @Scheduled(cron = "0 0/10 * * * ?")
    // @Scheduled(fixedRate = 5000) // 单位ms每5s执行一次
    @Scheduled(cron = "${TASK_DYNAMIC_CRON}")
    public void processAliyunIP6() {
        logger.info("定时任务开始执行....");
        IpInfoVO ipInfoVO = ipv6Interface.getNativeIpv6();
        logger.info("获取并打印本机ipv6={}", JSON.toJSONString(ipInfoVO));

        DescribeDomainRecordsResponse.Record record = null;
        if (CollectionUtil.isEmpty(recordMap)) { // map为空才去请求远端
            record = operateDomain.loadDomain(ipInfoVO);
            logger.info("recordMap中无记录，请求远端域名信息：{}", JSON.toJSONString(record));
            recordMap.put("record", record);
        } else {
            record = (DescribeDomainRecordsResponse.Record) recordMap.get("record");
            logger.info("recordMap中有记录，不用请求远端域名信息:{}", JSON.toJSONString(record));
        }

        //比较ip6
        if (!ipInfoVO.getIp6Value().equals(record.getValue())) { // 如果不同,更新远端和map
            logger.info("ip不同哈，开始更新ip...");
            record.setValue(ipInfoVO.getIp6Value());

            UpdateDomainRecordResponse response = operateDomain.updateDomain(record);
            String responseStr = JSON.toJSONString(response);
            logger.info("IP6ScheduleTask===>processAliyunIP6 is success;response:{}", responseStr);

            if (!StringUtils.isEmpty(responseStr) && responseStr.contains("requestId")
                    && responseStr.contains("recordId")) { // 说明更新远端成功，更新map记录
                recordMap.put("record", record);
            }
        } else {
            logger.info("ip相同哈，不用更新！ip6Value:{}", ipInfoVO.getIp6Value());
        }
        logger.info("定时任务执行完成....");
    }
}
